import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2024-09-28
 * Time: 20:52
 */
public class JDBC_Demo2 {
    public static void main(String[] args) {
        // 定义mysql数据源对象
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        // 设置数据连接串
        // url
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8" +
                "&allowPublicKeyRetrieval=true&useSSL=false");
        // 用户名
        mysqlDataSource.setUser("root");
        // 密码
        mysqlDataSource.setPassword("123456");


        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        // 上面是厂商给我们提供的实现类，我们要使用Java层面的数据源接口
        DataSource dataSource = mysqlDataSource; // 向上转型
        try {
            // 从数据源中获取连接
            connection = dataSource.getConnection();
            // 定义执行的SQL
            String sql = "select id, name, age, gender from student where name = ?"; // 使用占位符
            // 对SQL语句进行预编译
            preparedStatement = connection.prepareStatement(sql);
            // 接收输入数据
            System.out.print("请输入学生姓名：");
            Scanner scanner = new Scanner(System.in);
            String name = scanner.next();
            // 用真实数据代替占位符
            preparedStatement.setString(1,name);
            // 执行SQL语句并接收结果集
            resultSet = preparedStatement.executeQuery(); // 这里不要传入SQL了
            while (resultSet.next()) {
                long stuId = resultSet.getLong(1);
                String stuName = resultSet.getString(2);
                int stuAge = resultSet.getInt(3);
                byte stuGender = resultSet.getByte(4);
                System.out.println(MessageFormat.format("学生编号{0},学生姓名{1}, 学生年龄{2}, 学生性别{3}"
                        ,stuId, stuName, stuAge, stuGender));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
